home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / elispman.lha / elispman / elisp-8 (.txt) < prev    next >
GNU Info File  |  1993-06-01  |  51KB  |  939 lines

  1. This is Info file elisp, produced by Makeinfo-1.55 from the input file
  2. elisp.texi.
  3.    This is edition 2.0 of the GNU Emacs Lisp Reference Manual, for
  4. Emacs Version 19.
  5.    Published by the Free Software Foundation, 675 Massachusetts Avenue,
  6. Cambridge, MA 02139 USA
  7.    Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
  8.    Permission is granted to make and distribute verbatim copies of this
  9. manual provided the copyright notice and this permission notice are
  10. preserved on all copies.
  11.    Permission is granted to copy and distribute modified versions of
  12. this manual under the conditions for verbatim copying, provided that
  13. the entire resulting derived work is distributed under the terms of a
  14. permission notice identical to this one.
  15.    Permission is granted to copy and distribute translations of this
  16. manual into another language, under the above conditions for modified
  17. versions, except that this permission notice may be stated in a
  18. translation approved by the Foundation.
  19. File: elisp,  Node: Defining Variables,  Next: Accessing Variables,  Prev: Void Variables,  Up: Variables
  20. Defining Global Variables
  21. =========================
  22.    You may announce your intention to use a symbol as a global variable
  23. with a definition, using `defconst' or `defvar'.
  24.    In Emacs Lisp, definitions serve three purposes.  First, they inform
  25. the user who reads the code that certain symbols are *intended* to be
  26. used as variables.  Second, they inform the Lisp system of these things,
  27. supplying a value and documentation.  Third, they provide information to
  28. utilities such as `etags' and `make-docfile', which create data bases
  29. of the functions and variables in a program.
  30.    The difference between `defconst' and `defvar' is primarily a matter
  31. of intent, serving to inform human readers of whether programs will
  32. change the variable.  Emacs Lisp does not restrict the ways in which a
  33. variable can be used based on `defconst' or `defvar' declarations.
  34. However, it also makes a difference for initialization: `defconst'
  35. unconditionally initializes the variable, while `defvar' initializes it
  36. only if it is void.
  37.    One would expect user option variables to be defined with
  38. `defconst', since programs do not change them.  Unfortunately, this has
  39. bad results if the definition is in a library that is not preloaded:
  40. `defconst' would override any prior value when the library is loaded.
  41. Users would like to be able to set the option in their init files, and
  42. override the default value given in the definition.  For this reason,
  43. user options must be defined with `defvar'.
  44.  - Special Form: defvar SYMBOL [VALUE [DOC-STRING]]
  45.      This special form informs a person reading your code that SYMBOL
  46.      will be used as a variable that the programs are likely to set or
  47.      change.  It is also used for all user option variables except in
  48.      the preloaded parts of Emacs.  Note that SYMBOL is not evaluated;
  49.      the symbol to be defined must appear explicitly in the `defvar'.
  50.      If SYMBOL already has a value (i.e., it is not void), VALUE is not
  51.      even evaluated, and SYMBOL's value remains unchanged.  If SYMBOL
  52.      is void and VALUE is specified, it is evaluated and SYMBOL is set
  53.      to the result.  (If VALUE is not specified, the value of SYMBOL is
  54.      not changed in any case.)
  55.      If SYMBOL has a buffer-local binding in the current buffer,
  56.      `defvar' sets the default value, not the local value.
  57.      If the DOC-STRING argument appears, it specifies the documentation
  58.      for the variable.  (This opportunity to specify documentation is
  59.      one of the main benefits of defining the variable.)  The
  60.      documentation is stored in the symbol's `variable-documentation'
  61.      property.  The Emacs help functions (*note Documentation::.) look
  62.      for this property.
  63.      If the first character of DOC-STRING is `*', it means that this
  64.      variable is considered to be a user option.  This affects commands
  65.      such as `set-variable' and `edit-options'.
  66.      For example, this form defines `foo' but does not set its value:
  67.           (defvar foo)
  68.                => foo
  69.      The following example sets the value of `bar' to `23', and gives
  70.      it a documentation string:
  71.           (defvar bar 23
  72.             "The normal weight of a bar.")
  73.                => bar
  74.      The following form changes the documentation string for `bar',
  75.      making it a user option, but does not change the value, since `bar'
  76.      already has a value.  (The addition `(1+ 23)' is not even
  77.      performed.)
  78.           (defvar bar (1+ 23)
  79.             "*The normal weight of a bar.")
  80.                => bar
  81.           bar
  82.                => 23
  83.      Here is an equivalent expression for the `defvar' special form:
  84.           (defvar SYMBOL VALUE DOC-STRING)
  85.           ==
  86.           (progn
  87.             (if (not (boundp 'SYMBOL))
  88.                 (setq SYMBOL VALUE))
  89.             (put 'SYMBOL 'variable-documentation 'DOC-STRING)
  90.             'SYMBOL)
  91.      The `defvar' form returns SYMBOL, but it is normally used at top
  92.      level in a file where its value does not matter.
  93.  - Special Form: defconst SYMBOL [VALUE [DOC-STRING]]
  94.      This special form informs a person reading your code that SYMBOL
  95.      has a global value, established here, that will not normally be
  96.      changed or locally bound by the execution of the program.  The
  97.      user, however, may be welcome to change it.  Note that SYMBOL is
  98.      not evaluated; the symbol to be defined must appear explicitly in
  99.      the `defconst'.
  100.      `defconst' always evaluates VALUE and sets the global value of
  101.      SYMBOL to the result, provided VALUE is given.  If SYMBOL has a
  102.      buffer-local binding in the current buffer, `defconst' sets the
  103.      default value, not the local value.
  104.      *Please note:* don't use `defconst' for user option variables in
  105.      libraries that are not normally loaded.  The user should be able
  106.      to specify a value for such a variable in the `.emacs' file, so
  107.      that it will be in effect if and when the library is loaded later.
  108.      Here, `pi' is a constant that presumably ought not to be changed
  109.      by anyone (attempts by the Indiana State Legislature
  110.      notwithstanding).  As the second form illustrates, however, this
  111.      is only advisory.
  112.           (defconst pi 3 "Pi to one place.")
  113.                => pi
  114.           (setq pi 4)
  115.                => pi
  116.           pi
  117.                => 4
  118.  - Function: user-variable-p VARIABLE
  119.      This function returns `t' if VARIABLE is a user option, intended
  120.      to be set by the user for customization, `nil' otherwise.
  121.      (Variables other than user options exist for the internal purposes
  122.      of Lisp programs, and users need not know about them.)
  123.      User option variables are distinguished from other variables by the
  124.      first character of the `variable-documentation' property.  If the
  125.      property exists and is a string, and its first character is `*',
  126.      then the variable is a user option.
  127.    Note that if the `defconst' and `defvar' special forms are used
  128. while the variable has a local binding, the local binding's value is
  129. set, and the global binding is not changed.  This would be confusing.
  130. But the normal way to use these special forms is at top level in a file,
  131. where no local binding should be in effect.
  132. File: elisp,  Node: Accessing Variables,  Next: Setting Variables,  Prev: Defining Variables,  Up: Variables
  133. Accessing Variable Values
  134. =========================
  135.    The usual way to reference a variable is to write the symbol which
  136. names it (*note Symbol Forms::.).  This requires you to specify the
  137. variable name when you write the program.  Usually that is exactly what
  138. you want to do.  Occasionally you need to choose at run time which
  139. variable to reference; then you can use `symbol-value'.
  140.  - Function: symbol-value SYMBOL
  141.      This function returns the value of SYMBOL.  This is the value in
  142.      the innermost local binding of the symbol, or its global value if
  143.      it has no local bindings.
  144.           (setq abracadabra 5)
  145.                => 5
  146.           (setq foo 9)
  147.                => 9
  148.           
  149.           ;; Here the symbol `abracadabra'
  150.           ;;   is the symbol whose value is examined.
  151.           (let ((abracadabra 'foo))
  152.             (symbol-value 'abracadabra))
  153.                => foo
  154.           
  155.           ;; Here the value of `abracadabra',
  156.           ;;   which is `foo',
  157.           ;;   is the symbol whose value is examined.
  158.           (let ((abracadabra 'foo))
  159.             (symbol-value abracadabra))
  160.                => 9
  161.           
  162.           (symbol-value 'abracadabra)
  163.                => 5
  164.      A `void-variable' error is signaled if SYMBOL has neither a local
  165.      binding nor a global value.
  166. File: elisp,  Node: Setting Variables,  Next: Variable Scoping,  Prev: Accessing Variables,  Up: Variables
  167. How to Alter a Variable Value
  168. =============================
  169.    The usual way to change the value of a variable is with the special
  170. form `setq'.  When you need to compute the choice of variable at run
  171. time, use the function `set'.
  172.  - Special Form: setq [SYMBOL FORM]...
  173.      This special form is the most common method of changing a
  174.      variable's value.  Each SYMBOL is given a new value, which is the
  175.      result of evaluating the corresponding FORM.  The most-local
  176.      existing binding of the symbol is changed.
  177.      The value of the `setq' form is the value of the last FORM.
  178.           (setq x (1+ 2))
  179.                => 3
  180.           x                   ; `x' now has a global value.
  181.                => 3
  182.           (let ((x 5))
  183.             (setq x 6)        ; The local binding of `x' is set.
  184.             x)
  185.                => 6
  186.           x                   ; The global value is unchanged.
  187.                => 3
  188.      Note that the first FORM is evaluated, then the first SYMBOL is
  189.      set, then the second FORM is evaluated, then the second SYMBOL is
  190.      set, and so on:
  191.           (setq x 10          ; Notice that `x' is set before
  192.                 y (1+ x))     ;   the value of `y' is computed.
  193.                => 11
  194.  - Function: set SYMBOL VALUE
  195.      This function sets SYMBOL's value to VALUE, then returns VALUE.
  196.      Since `set' is a function, the expression written for SYMBOL is
  197.      evaluated to obtain the symbol to be set.
  198.      The most-local existing binding of the variable is the binding
  199.      that is set; shadowed bindings are not affected.  If SYMBOL is not
  200.      actually a symbol, a `wrong-type-argument' error is signaled.
  201.           (set one 1)
  202.           error--> Symbol's value as variable is void: one
  203.           (set 'one 1)
  204.                => 1
  205.           (set 'two 'one)
  206.                => one
  207.           (set two 2)         ; `two' evaluates to symbol `one'.
  208.                => 2
  209.           one                 ; So it is `one' that was set.
  210.                => 2
  211.           (let ((one 1))      ; This binding of `one' is set,
  212.             (set 'one 3)      ;   not the global value.
  213.             one)
  214.                => 3
  215.           one
  216.                => 2
  217.      Logically speaking, `set' is a more fundamental primitive that
  218.      `setq'.  Any use of `setq' can be trivially rewritten to use
  219.      `set'; `setq' could even be defined as a macro, given the
  220.      availability of `set'.  However, `set' itself is rarely used;
  221.      beginners hardly need to know about it.  It is needed only when the
  222.      choice of variable to be set is made at run time.  For example, the
  223.      command `set-variable', which reads a variable name from the user
  224.      and then sets the variable, needs to use `set'.
  225.           Common Lisp note: in Common Lisp, `set' always changes the
  226.           symbol's special value, ignoring any lexical bindings.  In
  227.           Emacs Lisp, all variables and all bindings are special, so
  228.           `set' always affects the most local existing binding.
  229. File: elisp,  Node: Variable Scoping,  Next: Buffer-Local Variables,  Prev: Setting Variables,  Up: Variables
  230. Scoping Rules for Variable Bindings
  231. ===================================
  232.    A given symbol `foo' may have several local variable bindings,
  233. established at different places in the Lisp program, as well as a global
  234. binding.  The most recently established binding takes precedence over
  235. the others.
  236.    Local bindings in Emacs Lisp have "indefinite scope" and "dynamic
  237. extent".  "Scope" refers to *where* textually in the source code the
  238. binding can be accessed.  Indefinite scope means that any part of the
  239. program can potentially access the variable binding.  "Extent" refers
  240. to *when*, as the program is executing, the binding exists.  Dynamic
  241. extent means that the binding lasts as long as the activation of the
  242. construct that established it.
  243.    The combination of dynamic extent and indefinite scope is called
  244. "dynamic scoping".  By contrast, most programming languages use
  245. "lexical scoping", in which references to a local variable must be
  246. textually within the function or block that binds the variable.
  247.      Common Lisp note: variables declared "special" in Common Lisp are
  248.      dynamically scoped like variables in Emacs Lisp.
  249. * Menu:
  250. * Scope::          Scope means where in the program a value is visible.
  251.                      Comparison with other languages.
  252. * Extent::         Extent means how long in time a value exists.
  253. * Impl of Scope::  Two ways to implement dynamic scoping.
  254. * Using Scoping::  How to use dynamic scoping carefully and avoid problems.
  255. File: elisp,  Node: Scope,  Next: Extent,  Prev: Variable Scoping,  Up: Variable Scoping
  256. Scope
  257. -----
  258.    Emacs Lisp uses "indefinite scope" for local variable bindings.
  259. This means that any function anywhere in the program text might access a
  260. given binding of a variable.  Consider the following function
  261. definitions:
  262.      (defun binder (x)   ; `x' is bound in `binder'.
  263.         (foo 5))         ; `foo' is some other function.
  264.      
  265.      (defun user ()      ; `x' is used in `user'.
  266.        (list x))
  267.    In a lexically scoped language, the binding of `x' from `binder'
  268. would never be accessible in `user', because `user' is not textually
  269. contained within the function `binder'.  However, in dynamically scoped
  270. Emacs Lisp, `user' may or may not refer to the binding of `x'
  271. established in `binder', depending on circumstances:
  272.    * If we call `user' directly without calling `binder' at all, then
  273.      whatever binding of `x' is found, it cannot come from `binder'.
  274.    * If we define `foo' as follows and call `binder', then the binding
  275.      made in `binder' will be seen in `user':
  276.           (defun foo (lose)
  277.             (user))
  278.    * If we define `foo' as follows and call `binder', then the binding
  279.      made in `binder' *will not* be seen in `user':
  280.           (defun foo (x)
  281.             (user))
  282.      Here, when `foo' is called by `binder', it binds `x'.  (The
  283.      binding in `foo' is said to "shadow" the one made in `binder'.)
  284.      Therefore, `user' will access the `x' bound by `foo' instead of
  285.      the one bound by `binder'.
  286. File: elisp,  Node: Extent,  Next: Impl of Scope,  Prev: Scope,  Up: Variable Scoping
  287. Extent
  288. ------
  289.    "Extent" refers to the time during program execution that a variable
  290. name is valid.  In Emacs Lisp, a variable is valid only while the form
  291. that bound it is executing.  This is called "dynamic extent".  "Local"
  292. or "automatic" variables in most languages, including C and Pascal,
  293. have dynamic extent.
  294.    One alternative to dynamic extent is "indefinite extent".  This
  295. means that a variable binding can live on past the exit from the form
  296. that made the binding.  Common Lisp and Scheme, for example, support
  297. this, but Emacs Lisp does not.
  298.    To illustrate this, the function below, `make-add', returns a
  299. function that purports to add N to its own argument M.  This would work
  300. in Common Lisp, but it does not work as intended in Emacs Lisp, because
  301. after the call to `make-add' exits, the variable `n' is no longer bound
  302. to the actual argument 2.
  303.      (defun make-add (n)
  304.          (function (lambda (m) (+ n m))))  ; Return a function.
  305.           => make-add
  306.      (fset 'add2 (make-add 2))  ; Define function `add2'
  307.                                 ;   with `(make-add 2)'.
  308.           => (lambda (m) (+ n m))
  309.      (add2 4)                   ; Try to add 2 to 4.
  310.      error--> Symbol's value as variable is void: n
  311. File: elisp,  Node: Impl of Scope,  Next: Using Scoping,  Prev: Extent,  Up: Variable Scoping
  312. Implementation of Dynamic Scoping
  313. ---------------------------------
  314.    A simple sample implementation (which is not how Emacs Lisp actually
  315. works) may help you understand dynamic binding.  This technique is
  316. called "deep binding" and was used in early Lisp systems.
  317.    Suppose there is a stack of bindings: variable-value pairs.  At entry
  318. to a function or to a `let' form, we can push bindings on the stack for
  319. the arguments or local variables created there.  We can pop those
  320. bindings from the stack at exit from the binding construct.
  321.    We can find the value of a variable by searching the stack from top
  322. to bottom for a binding for that variable; the value from that binding
  323. is the value of the variable.  To set the variable, we search for the
  324. current binding, then store the new value into that binding.
  325.    As you can see, a function's bindings remain in effect as long as it
  326. continues execution, even during its calls to other functions.  That is
  327. why we say the extent of the binding is dynamic.  And any other function
  328. can refer to the bindings, if it uses the same variables while the
  329. bindings are in effect.  That is why we say the scope is indefinite.
  330.    The actual implementation of variable scoping in GNU Emacs Lisp uses
  331. a technique called "shallow binding".  Each variable has a standard
  332. place in which its current value is always found--the value cell of the
  333. symbol.
  334.    In shallow binding, setting the variable works by storing a value in
  335. the value cell.  When a new local binding is created, the local value is
  336. stored in the value cell, and the old value (belonging to a previous
  337. binding) is pushed on a stack.  When a binding is eliminated, the old
  338. value is popped off the stack and stored in the value cell.
  339.    We use shallow binding because it has the same results as deep
  340. binding, but runs faster, since there is never a need to search for a
  341. binding.
  342. File: elisp,  Node: Using Scoping,  Prev: Impl of Scope,  Up: Variable Scoping
  343. Proper Use of Dynamic Scoping
  344. -----------------------------
  345.    Binding a variable in one function and using it in another is a
  346. powerful technique, but if used without restraint, it can make programs
  347. hard to understand.  There are two clean ways to use this technique:
  348.    * Use or bind the variable only in a few related functions, written
  349.      close together in one file.  Such a variable is used for
  350.      communication within one program.
  351.      You should write comments to inform other programmers that they
  352.      can see all uses of the variable before them, and to advise them
  353.      not to add uses elsewhere.
  354.    * Give the variable a well-defined, documented meaning, and make all
  355.      appropriate functions refer to it (but not bind it or set it)
  356.      wherever that meaning is relevant.  For example, the variable
  357.      `case-fold-search' is defined as "non-`nil' means ignore case when
  358.      searching"; various search and replace functions refer to it
  359.      directly or through their subroutines, but do not bind or set it.
  360.      Then you can bind the variable in other programs, knowing reliably
  361.      what the effect will be.
  362. File: elisp,  Node: Buffer-Local Variables,  Prev: Variable Scoping,  Up: Variables
  363. Buffer-Local Variables
  364. ======================
  365.    Global and local variable bindings are found in most programming
  366. languages in one form or another.  Emacs also supports another, unusual
  367. kind of variable binding: "buffer-local" bindings, which apply only to
  368. one buffer.  Emacs Lisp is meant for programming editing commands, and
  369. having different values for a variable in different buffers is an
  370. important customization method.
  371. * Menu:
  372. * Intro to Buffer-Local::      Introduction and concepts.
  373. * Creating Buffer-Local::      Creating and destroying buffer-local bindings.
  374. * Default Value::              The default value is seen in buffers
  375.                                  that don't have their own local values.
  376. File: elisp,  Node: Intro to Buffer-Local,  Next: Creating Buffer-Local,  Prev: Buffer-Local Variables,  Up: Buffer-Local Variables
  377. Introduction to Buffer-Local Variables
  378. --------------------------------------
  379.    A buffer-local variable has a buffer-local binding associated with a
  380. particular buffer.  The binding is in effect when that buffer is
  381. current; otherwise, it is not in effect.  If you set the variable while
  382. a buffer-local binding is in effect, the new value goes in that binding,
  383. so the global binding is unchanged; this means that the change is
  384. visible in that buffer alone.
  385.    A variable may have buffer-local bindings in some buffers but not in
  386. others.  The global binding is shared by all the buffers that don't have
  387. their own bindings.  Thus, if you set the variable in a buffer that does
  388. not have a buffer-local binding for it, the new value is visible in all
  389. buffers except those with buffer-local bindings.  (Here we are assuming
  390. that there are no `let'-style local bindings to complicate the issue.)
  391.    The most common use of buffer-local bindings is for major modes to
  392. change variables that control the behavior of commands.  For example, C
  393. mode and Lisp mode both set the variable `paragraph-start' to specify
  394. that only blank lines separate paragraphs.  They do this by making the
  395. variable buffer-local in the buffer that is being put into C mode or
  396. Lisp mode, and then setting it to the new value for that mode.
  397.    The usual way to make a buffer-local binding is with
  398. `make-local-variable', which is what major mode commands use.  This
  399. affects just the current buffer; all other buffers (including those yet
  400. to be created) continue to share the global value.
  401.    A more powerful operation is to mark the variable as "automatically
  402. buffer-local" by calling `make-variable-buffer-local'.  You can think
  403. of this as making the variable local in all buffers, even those yet to
  404. be created.  More precisely, the effect is that setting the variable
  405. automatically makes the variable local to the current buffer if it is
  406. not already so.  All buffers start out by sharing the global value of
  407. the variable as usual, but any `setq' creates a buffer-local binding
  408. for the current buffer.  The new value is stored in the buffer-local
  409. binding, leaving the (default) global binding untouched.  The global
  410. value can no longer be changed with `setq'; you need to use
  411. `setq-default' to do that.
  412.    *Warning:* when a variable has local values in one or more buffers,
  413. you can get Emacs very confused by binding the variable with `let',
  414. changing to a different current buffer in which a different binding is
  415. in effect, and then exiting the `let'.  To preserve your sanity, it is
  416. wise to avoid such situations.  If you use `save-excursion' around each
  417. piece of code that changes to a different current buffer, you will not
  418. have this problem.  Here is an example of incorrect code:
  419.      (setq foo 'b)
  420.      (set-buffer "a")
  421.      (make-local-variable 'foo)
  422.      (setq foo 'a)
  423.      (let ((foo 'temp))
  424.        (set-buffer "b")
  425.        ...)
  426.      foo => 'a      ; The old buffer-local value from buffer `a'
  427.                     ;   is now the default value.
  428.      (set-buffer "a")
  429.      foo => 'temp   ; The local value that should be gone
  430.                     ;   is now the buffer-local value in buffer `a'.
  431. But `save-excursion' as shown here avoids the problem:
  432.      (let ((foo 'temp))
  433.        (save-excursion
  434.          (set-buffer "b")
  435.          ...))
  436.    Local variables in a file you edit are also represented by
  437. buffer-local bindings for the buffer that holds the file within Emacs.
  438. *Note Auto Major Mode::.
  439. File: elisp,  Node: Creating Buffer-Local,  Next: Default Value,  Prev: Intro to Buffer-Local,  Up: Buffer-Local Variables
  440. Creating and Destroying Buffer-local Bindings
  441. ---------------------------------------------
  442.  - Command: make-local-variable VARIABLE
  443.      This function creates a buffer-local binding in the current buffer
  444.      for VARIABLE (a symbol).  Other buffers are not affected.  The
  445.      value returned is VARIABLE.
  446.      The buffer-local value of VARIABLE starts out as the same value
  447.      VARIABLE previously had.  If VARIABLE was void, it remains void.
  448.           ;; In buffer `b1':
  449.           (setq foo 5)                ; Affects all buffers.
  450.                => 5
  451.           (make-local-variable 'foo)  ; Now it is local in `b1'.
  452.                => foo
  453.           foo                         ; That did not change
  454.                => 5                   ;   the value.
  455.           (setq foo 6)                ; Change the value
  456.                => 6                   ;   in `b1'.
  457.           foo
  458.                => 6
  459.           
  460.           ;; In buffer `b2', the value hasn't changed.
  461.           (save-excursion
  462.             (set-buffer "b2")
  463.             foo)
  464.                => 5
  465.  - Command: make-variable-buffer-local VARIABLE
  466.      This function marks VARIABLE (a symbol) automatically
  467.      buffer-local, so that any attempt to set it will make it local to
  468.      the current buffer at the time.
  469.      The value returned is VARIABLE.
  470.  - Function: buffer-local-variables &optional BUFFER
  471.      This function tells you what the buffer-local variables are in
  472.      buffer BUFFER.  It returns an association list (*note Association
  473.      Lists::.) in which each association contains one buffer-local
  474.      variable and its value.  If BUFFER is omitted, the current buffer
  475.      is used.
  476.           (setq lcl (buffer-local-variables))
  477.           => ((fill-column . 75)
  478.               (case-fold-search . t)
  479.               ...
  480.               (mark-ring #<marker at 5454 in buffers.texi>)
  481.               (require-final-newline . t))
  482.      Note that storing new values into the CDRs of the elements in this
  483.      list does *not* change the local values of the variables.
  484.  - Command: kill-local-variable VARIABLE
  485.      This function deletes the buffer-local binding (if any) for
  486.      VARIABLE (a symbol) in the current buffer.  As a result, the
  487.      global (default) binding of VARIABLE becomes visible in this
  488.      buffer.  Usually this results in a change in the value of
  489.      VARIABLE, since the global value is usually different from the
  490.      buffer-local value just eliminated.
  491.      It is possible to kill the local binding of a variable that
  492.      automatically becomes local when set.  This causes the variable to
  493.      show its global value in the current buffer.  However, if you set
  494.      the variable again, this will once again create a local value.
  495.      `kill-local-variable' returns VARIABLE.
  496.  - Function: kill-all-local-variables
  497.      This function eliminates all the buffer-local variable bindings of
  498.      the current buffer except for variables marker as "permanent".  As
  499.      a result, the buffer will see the default values of most variables.
  500.      This function also resets certain other information pertaining to
  501.      the buffer: its local keymap is set to `nil', its syntax table is
  502.      set to the value of `standard-syntax-table', and its abbrev table
  503.      is set to the value of `fundamental-mode-abbrev-table'.
  504.      Every major mode command begins by calling this function, which
  505.      has the effect of switching to Fundamental mode and erasing most
  506.      of the effects of the previous major mode.  To ensure that this
  507.      does its job, the variables that major modes set should not be
  508.      marked permanent.
  509.      `kill-all-local-variables' returns `nil'.
  510.    A local variable is "permanent" if the variable name (a symbol) has a
  511. `permanent-local' property that is non-`nil'.  Permanent locals are
  512. appropriate for data pertaining to where the file came from or how to
  513. save it, rather than with how to edit the contents.
  514. File: elisp,  Node: Default Value,  Prev: Creating Buffer-Local,  Up: Buffer-Local Variables
  515. The Default Value of a Buffer-Local Variable
  516. --------------------------------------------
  517.    The global value of a variable with buffer-local bindings is also
  518. called the "default" value, because it is the value that is in effect
  519. except when specifically overridden.
  520.    The functions `default-value' and `setq-default' allow you to access
  521. and change the default value regardless of whether the current buffer
  522. has a buffer-local binding.  For example, you could use `setq-default'
  523. to change the default setting of `paragraph-start' for most buffers;
  524. and this would work even when you are in a C or Lisp mode buffer which
  525. has a buffer-local value for this variable.
  526.    The special forms `defvar' and `defconst' also set the default value
  527. (if they set the variable at all), rather than any local value.
  528.  - Function: default-value SYMBOL
  529.      This function returns SYMBOL's default value.  This is the value
  530.      that is seen in buffers that do not have their own values for this
  531.      variable.  If SYMBOL is not buffer-local, this is equivalent to
  532.      `symbol-value' (*note Accessing Variables::.).
  533.  - Function: default-boundp VARIABLE
  534.      The function `default-boundp' tells you whether VARIABLE's default
  535.      value is nonvoid.  If `(default-boundp 'foo)' returns `nil', then
  536.      `(default-value 'foo)' would get an error.
  537.      `default-boundp' is to `default-value' as `boundp' is to
  538.      `symbol-value'.
  539.  - Special Form: setq-default SYMBOL VALUE
  540.      This sets the default value of SYMBOL to VALUE.  SYMBOL is not
  541.      evaluated, but VALUE is.  The value of the `setq-default' form is
  542.      VALUE.
  543.      If a SYMBOL is not buffer-local for the current buffer, and is not
  544.      marked automatically buffer-local, this has the same effect as
  545.      `setq'.  If SYMBOL is buffer-local for the current buffer, then
  546.      this changes the value that other buffers will see (as long as they
  547.      don't have a buffer-local value), but not the value that the
  548.      current buffer sees.
  549.           ;; In buffer `foo':
  550.           (make-local-variable 'local)
  551.                => local
  552.           (setq local 'value-in-foo)
  553.                => value-in-foo
  554.           (setq-default local 'new-default)
  555.                => new-default
  556.           local
  557.                => value-in-foo
  558.           (default-value 'local)
  559.                => new-default
  560.           
  561.           ;; In (the new) buffer `bar':
  562.           local
  563.                => new-default
  564.           (default-value 'local)
  565.                => new-default
  566.           (setq local 'another-default)
  567.                => another-default
  568.           (default-value 'local)
  569.                => another-default
  570.           
  571.           ;; Back in buffer `foo':
  572.           local
  573.                => value-in-foo
  574.           (default-value 'local)
  575.                => another-default
  576.  - Function: set-default SYMBOL VALUE
  577.      This function is like `setq-default', except that SYMBOL is
  578.      evaluated.
  579.           (set-default (car '(a b c)) 23)
  580.                => 23
  581.           (default-value 'a)
  582.                => 23
  583. File: elisp,  Node: Functions,  Next: Macros,  Prev: Variables,  Up: Top
  584. Functions
  585. *********
  586.    A Lisp program is composed mainly of Lisp functions.  This chapter
  587. explains what functions are, how they accept arguments, and how to
  588. define them.
  589. * Menu:
  590. * What Is a Function::    Lisp functions vs. primitives; terminology.
  591. * Lambda Expressions::    How functions are expressed as Lisp objects.
  592. * Function Names::        A symbol can serve as the name of a function.
  593. * Defining Functions::    Lisp expressions for defining functions.
  594. * Calling Functions::     How to use an existing function.
  595. * Mapping Functions::     Applying a function to each element of a list, etc.
  596. * Anonymous Functions::   Lambda expressions are functions with no names.
  597. * Function Cells::        Accessing or setting the function definition
  598.                             of a symbol.
  599. * Inline Functions::      Defining functions that the compiler will open code.
  600. * Related Topics::        Cross-references to specific Lisp primitives
  601.                             that have a special bearing on how functions work.
  602. File: elisp,  Node: What Is a Function,  Next: Lambda Expressions,  Up: Functions
  603. What Is a Function?
  604. ===================
  605.    In a general sense, a function is a rule for carrying on a
  606. computation given several values called "arguments".  The result of the
  607. computation is called the value of the function.  The computation can
  608. also have side effects: lasting changes in the values of variables or
  609. the contents of data structures.
  610.    Here are important terms for functions in Emacs Lisp and for other
  611. function-like objects.
  612. "function"
  613.      In Emacs Lisp, a "function" is anything that can be applied to
  614.      arguments in a Lisp program.  In some cases, we use it more
  615.      specifically to mean a function written in Lisp.  Special forms and
  616.      macros are not functions.
  617. "primitive"
  618.      A "primitive" is a function callable from Lisp that is written in
  619.      C, such as `car' or `append'.  These functions are also called
  620.      "built-in" functions or "subrs".  (Special forms are also
  621.      considered primitives.)
  622.      Usually the reason that a function is a primitives is because it is
  623.      fundamental, or provides a low-level interface to operating system
  624.      services, or because it needs to run fast.  Primitives can be
  625.      modified or added only by changing the C sources and recompiling
  626.      the editor.  See *Note Writing Emacs Primitives::.
  627. "lambda expression"
  628.      A "lambda expression" is a function written in Lisp.  These are
  629.      described in the following section.  *Note Lambda Expressions::.
  630. "special form"
  631.      A "special form" is a primitive that is like a function but does
  632.      not evaluate all of its arguments in the usual way.  It may
  633.      evaluate only some of the arguments, or may evaluate them in an
  634.      unusual order, or several times.  Many special forms are described
  635.      in *Note Control Structures::.
  636. "macro"
  637.      A "macro" is a construct defined in Lisp by the programmer.  It
  638.      differs from a function in that it translates a Lisp expression
  639.      that you write into an equivalent expression to be evaluated
  640.      instead of the original expression.  *Note Macros::, for how to
  641.      define and use macros.
  642. "command"
  643.      A "command" is an object that `command-execute' can invoke; it is
  644.      a possible definition for a key sequence.  Some functions are
  645.      commands; a function written in Lisp is a command if it contains an
  646.      interactive declaration (*note Defining Commands::.).  Such a
  647.      function can be called from Lisp expressions like other functions;
  648.      in this case, the fact that the function is a command makes no
  649.      difference.
  650.      Strings are commands also, even though they are not functions.  A
  651.      symbol is a command if its function definition is a command; such
  652.      symbols can be invoked with `M-x'.  The symbol is a function as
  653.      well if the definition is a function.  *Note Command Overview::.
  654. "keystroke command"
  655.      A "keystroke command" is a command that is bound to a key sequence
  656.      (typically one to three keystrokes).  The distinction is made here
  657.      merely to avoid confusion with the meaning of "command" in
  658.      non-Emacs editors; for programmers, the distinction is normally
  659.      unimportant.
  660. "byte-code function"
  661.      A "byte-code function" is a function that has been compiled by the
  662.      byte compiler.  *Note Byte-Code Type::.
  663.  - Function: subrp OBJECT
  664.      This function returns `t' if OBJECT is a built-in function (i.e. a
  665.      Lisp primitive).
  666.           (subrp 'message)            ; `message' is a symbol,
  667.                => nil                 ;   not a subr object.
  668.           (subrp (symbol-function 'message))
  669.                => t
  670.  - Function: byte-code-function-p OBJECT
  671.      This function returns `t' if OBJECT is a byte-code function.  For
  672.      example:
  673.           (byte-code-function-p (symbol-function 'next-line))
  674.                => t
  675. File: elisp,  Node: Lambda Expressions,  Next: Function Names,  Prev: What Is a Function,  Up: Functions
  676. Lambda Expressions
  677. ==================
  678.    A function written in Lisp is a list that looks like this:
  679.      (lambda (ARG-VARIABLES...)
  680.        [DOCUMENTATION-STRING]
  681.        [INTERACTIVE-DECLARATION]
  682.        BODY-FORMS...)
  683. (Such a list is called a "lambda expression" for historical reasons,
  684. even though it is not really an expression at all--it is not a form
  685. that can be evaluated meaningfully.)
  686. * Menu:
  687. * Lambda Components::       The parts of a lambda expression.
  688. * Simple Lambda::           A simple example.
  689. * Argument List::           Details and special features of argument lists.
  690. * Function Documentation::  How to put documentation in a function.
  691. File: elisp,  Node: Lambda Components,  Next: Simple Lambda,  Up: Lambda Expressions
  692. Components of a Lambda Expression
  693. ---------------------------------
  694.    A function written in Lisp (a "lambda expression") is a list that
  695. looks like this:
  696.      (lambda (ARG-VARIABLES...)
  697.        [DOCUMENTATION-STRING]
  698.        [INTERACTIVE-DECLARATION]
  699.        BODY-FORMS...)
  700.    The first element of a lambda expression is always the symbol
  701. `lambda'.  This indicates that the list represents a function.  The
  702. reason functions are defined to start with `lambda' is so that other
  703. lists, intended for other uses, will not accidentally be valid as
  704. functions.
  705.    The second element is a list of argument variable names (symbols).
  706. This is called the "lambda list".  When a Lisp function is called, the
  707. argument values are matched up against the variables in the lambda
  708. list, which are given local bindings with the values provided.  *Note
  709. Local Variables::.
  710.    The documentation string is an actual string that serves to describe
  711. the function for the Emacs help facilities.  *Note Function
  712. Documentation::.
  713.    The interactive declaration is a list of the form `(interactive
  714. CODE-STRING)'.  This declares how to provide arguments if the function
  715. is used interactively.  Functions with this declaration are called
  716. "commands"; they can be called using `M-x' or bound to a key.
  717. Functions not intended to be called in this way should not have
  718. interactive declarations.  *Note Defining Commands::, for how to write
  719. an interactive declaration.
  720.    The rest of the elements are the "body" of the function: the Lisp
  721. code to do the work of the function (or, as a Lisp programmer would say,
  722. "a list of Lisp forms to evaluate").  The value returned by the
  723. function is the value returned by the last element of the body.
  724. File: elisp,  Node: Simple Lambda,  Next: Argument List,  Prev: Lambda Components,  Up: Lambda Expressions
  725. A Simple Lambda-Expression Example
  726. ----------------------------------
  727.    Consider for example the following function:
  728.      (lambda (a b c) (+ a b c))
  729. We can call this function by writing it as the CAR of an expression,
  730. like this:
  731.      ((lambda (a b c) (+ a b c))
  732.       1 2 3)
  733. The body of this lambda expression is evaluated with the variable `a'
  734. bound to 1, `b' bound to 2, and `c' bound to 3.  Evaluation of the body
  735. adds these three numbers, producing the result 6; therefore, this call
  736. to the function returns the value 6.
  737.    Note that the arguments can be the results of other function calls,
  738. as in this example:
  739.      ((lambda (a b c) (+ a b c))
  740.       1 (* 2 3) (- 5 4))
  741. Here all the arguments `1', `(* 2 3)', and `(- 5 4)' are evaluated,
  742. left to right.  Then the lambda expression is applied to the argument
  743. values 1, 6 and 1 to produce the value 8.
  744.    It is not often useful to write a lambda expression as the CAR of a
  745. form in this way.  You can get the same result, of making local
  746. variables and giving them values, using the special form `let' (*note
  747. Local Variables::.).  And `let' is clearer and easier to use.  In
  748. practice, lambda expressions are either stored as the function
  749. definitions of symbols, to produce named functions, or passed as
  750. arguments to other functions (*note Anonymous Functions::.).
  751.    However, calls to explicit lambda expressions were very useful in the
  752. old days of Lisp, before the special form `let' was invented.  At that
  753. time, they were the only way to bind and initialize local variables.
  754. File: elisp,  Node: Argument List,  Next: Function Documentation,  Prev: Simple Lambda,  Up: Lambda Expressions
  755. Advanced Features of Argument Lists
  756. -----------------------------------
  757.    Our simple sample function, `(lambda (a b c) (+ a b c))', specifies
  758. three argument variables, so it must be called with three arguments: if
  759. you try to call it with only two arguments or four arguments, you get a
  760. `wrong-number-of-arguments' error.
  761.    It is often convenient to write a function that allows certain
  762. arguments to be omitted.  For example, the function `substring' accepts
  763. three arguments--a string, the start index and the end index--but the
  764. third argument defaults to the end of the string if you omit it.  It is
  765. also convenient for certain functions to accept an indefinite number of
  766. arguments, as the functions `and' and `+' do.
  767.    To specify optional arguments that may be omitted when a function is
  768. called, simply include the keyword `&optional' before the optional
  769. arguments.  To specify a list of zero or more extra arguments, include
  770. the keyword `&rest' before one final argument.
  771.    Thus, the complete syntax for an argument list is as follows:
  772.      (REQUIRED-VARS...
  773.       [&optional OPTIONAL-VARS...]
  774.       [&rest REST-VAR])
  775. The square brackets indicate that the `&optional' and `&rest' clauses,
  776. and the variables that follow them, are optional.
  777.    A call to the function requires one actual argument for each of the
  778. REQUIRED-VARS.  There may be actual arguments for zero or more of the
  779. OPTIONAL-VARS, and there cannot be any more actual arguments than these
  780. unless `&rest' exists.  In that case, there may be any number of extra
  781. actual arguments.
  782.    If actual arguments for the optional and rest variables are omitted,
  783. then they always default to `nil'.  However, the body of the function
  784. is free to consider `nil' an abbreviation for some other meaningful
  785. value.  This is what `substring' does; `nil' as the third argument
  786. means to use the length of the string supplied.  There is no way for the
  787. function to distinguish between an explicit argument of `nil' and an
  788. omitted argument.
  789.      Common Lisp note: Common Lisp allows the function to specify what
  790.      default value to use when an optional argument is omitted; GNU
  791.      Emacs Lisp always uses `nil'.
  792.    For example, an argument list that looks like this:
  793.      (a b &optional c d &rest e)
  794. binds `a' and `b' to the first two actual arguments, which are
  795. required.  If one or two more arguments are provided, `c' and `d' are
  796. bound to them respectively; any arguments after the first four are
  797. collected into a list and `e' is bound to that list.  If there are only
  798. two arguments, `c' is `nil'; if two or three arguments, `d' is `nil';
  799. if four arguments or fewer, `e' is `nil'.
  800.    There is no way to have required arguments following optional
  801. ones--it would not make sense.  To see why this must be so, suppose
  802. that `c' in the example were optional and `d' were required.  If three
  803. actual arguments are given; then which variable would the third
  804. argument be for?  Similarly, it makes no sense to have any more
  805. arguments (either required or optional) after a `&rest' argument.
  806.    Here are some examples of argument lists and proper calls:
  807.      ((lambda (n) (1+ n))                ; One required:
  808.       1)                                 ; requires exactly one argument.
  809.           => 2
  810.      ((lambda (n &optional n1)           ; One required and one optional:
  811.               (if n1 (+ n n1) (1+ n)))   ; 1 or 2 arguments.
  812.       1 2)
  813.           => 3
  814.      ((lambda (n &rest ns)               ; One required and one rest:
  815.               (+ n (apply '+ ns)))       ; 1 or more arguments.
  816.       1 2 3 4 5)
  817.           => 15
  818. File: elisp,  Node: Function Documentation,  Prev: Argument List,  Up: Lambda Expressions
  819. Documentation Strings of Functions
  820. ----------------------------------
  821.    A lambda expression may optionally have a "documentation string" just
  822. after the lambda list.  This string does not affect execution of the
  823. function; it is a kind of comment, but a systematized comment which
  824. actually appears inside the Lisp world and can be used by the Emacs help
  825. facilities.  *Note Documentation::, for how the DOCUMENTATION-STRING is
  826. accessed.
  827.    It is a good idea to provide documentation strings for all commands,
  828. and for all other functions in your program that users of your program
  829. should know about; internal functions might as well have only comments,
  830. since comments don't take up any room when your program is loaded.
  831.    The first line of the documentation string should stand on its own,
  832. because `apropos' displays just this first line.  It should consist of
  833. one or two complete sentences that summarize the function's purpose.
  834.    The start of the documentation string is usually indented, but since
  835. these spaces come before the starting double-quote, they are not part of
  836. the string.  Some people make a practice of indenting any additional
  837. lines of the string so that the text lines up.  *This is a mistake.*
  838. The indentation of the following lines is inside the string; what looks
  839. nice in the source code will look ugly when displayed by the help
  840. commands.
  841.    You may wonder how the documentation string could be optional, since
  842. there are required components of the function that follow it (the body).
  843. Since evaluation of a string returns that string, without any side
  844. effects, it has no effect if it is not the last form in the body.
  845. Thus, in practice, there is no confusion between the first form of the
  846. body and the documentation string; if the only body form is a string
  847. then it serves both as the return value and as the documentation.
  848. File: elisp,  Node: Function Names,  Next: Defining Functions,  Prev: Lambda Expressions,  Up: Functions
  849. Naming a Function
  850. =================
  851.    In most computer languages, every function has a name; the idea of a
  852. function without a name is nonsensical.  In Lisp, a function in the
  853. strictest sense has no name.  It is simply a list whose first element is
  854. `lambda', or a primitive subr-object.
  855.    However, a symbol can serve as the name of a function.  This happens
  856. when you put the function in the symbol's "function cell" (*note Symbol
  857. Components::.).  Then the symbol itself becomes a valid, callable
  858. function, equivalent to the list or subr-object that its function cell
  859. refers to.  The contents of the function cell are also called the
  860. symbol's "function definition".  When the evaluator finds the function
  861. definition to use in place of the symbol, we call that "symbol function
  862. indirection"; see *Note Function Indirection::.
  863.    In practice, nearly all functions are given names in this way and
  864. referred to through their names.  For example, the symbol `car' works
  865. as a function and does what it does because the primitive subr-object
  866. `#<subr car>' is stored in its function cell.
  867.    We give functions names because it is more convenient to refer to
  868. them by their names in other functions.  For primitive subr-objects
  869. such as `#<subr car>', names are the only way you can refer to them:
  870. there is no read syntax for such objects.  For functions written in
  871. Lisp, the name is more convenient to use in a call than an explicit
  872. lambda expression.  Also, a function with a name can refer to
  873. itself--it can be recursive.  Writing the function's name in its own
  874. definition is much more convenient than making the function definition
  875. point to itself (something that is not impossible but that has various
  876. disadvantages in practice).
  877.    Functions are often identified with the symbols used to name them.
  878. For example, we often speak of "the function `car'", not distinguishing
  879. between the symbol `car' and the primitive subr-object that is its
  880. function definition.  For most purposes, there is no need to
  881. distinguish.
  882.    Even so, keep in mind that a function need not have a unique name.
  883. While a given function object *usually* appears in the function cell of
  884. only one symbol, this is just a matter of convenience.  It is easy to
  885. store it in several symbols using `fset'; then each of the symbols is
  886. equally well a name for the same function.
  887.    A symbol used as a function name may also be used as a variable;
  888. these two uses of a symbol are independent and do not conflict.
  889. File: elisp,  Node: Defining Functions,  Next: Calling Functions,  Prev: Function Names,  Up: Functions
  890. Defining Named Functions
  891. ========================
  892.    We usually give a name to a function when it is first created.  This
  893. is called "defining a function", and it is done with the `defun'
  894. special form.
  895.  - Special Form: defun NAME ARGUMENT-LIST BODY-FORMS
  896.      `defun' is the usual way to define new Lisp functions.  It defines
  897.      the symbol NAME as a function that looks like this:
  898.           (lambda ARGUMENT-LIST . BODY-FORMS)
  899.      This lambda expression is stored in the function cell of NAME.
  900.      The value returned by evaluating the `defun' form is NAME, but
  901.      usually we ignore this value.
  902.      As described previously (*note Lambda Expressions::.),
  903.      ARGUMENT-LIST is a list of argument names and may include the
  904.      keywords `&optional' and `&rest'.  Also, the first two forms in
  905.      BODY-FORMS may be a documentation string and an interactive
  906.      declaration.
  907.      Note that the same symbol NAME may also be used as a global
  908.      variable, since the value cell is independent of the function cell.
  909.      Here are some examples:
  910.           (defun foo () 5)
  911.                => foo
  912.           (foo)
  913.                => 5
  914.           
  915.           (defun bar (a &optional b &rest c)
  916.               (list a b c))
  917.                => bar
  918.           (bar 1 2 3 4 5)
  919.                => (1 2 (3 4 5))
  920.           (bar 1)
  921.                => (1 nil nil)
  922.           (bar)
  923.           error--> Wrong number of arguments.
  924.           
  925.           (defun capitalize-backwards ()
  926.             "Upcase the last letter of a word."
  927.             (interactive)
  928.             (backward-word 1)
  929.             (forward-word 1)
  930.             (backward-char 1)
  931.             (capitalize-word 1))
  932.                => capitalize-backwards
  933.      Be careful not to redefine existing functions unintentionally.
  934.      `defun' redefines even primitive functions such as `car' without
  935.      any hesitation or notification.  Redefining a function already
  936.      defined is often done deliberately, and there is no way to
  937.      distinguish deliberate redefinition from unintentional
  938.      redefinition.
  939.